package io.gitee.chearnee.fw.datasecurity.core.handler.desensitization;


import io.gitee.chearnee.fw.datasecurity.core.enums.NumEnum;
import io.gitee.chearnee.fw.datasecurity.core.sidecar.SafeSideCarHelper;

import java.lang.annotation.Annotation;
import java.util.Objects;

/**
 * @author cn
 * @version 1.0
 * @description
 * @date 11/9/2022 5:09 PM
 */
public interface SDRuleHandler<T extends Annotation> {

    Class<T> getAnnotationType();

    /**
     * 脱敏
     *
     * @return
     */
    String masking(T t, String object);

    default String mask(T t, String object) {
        SafeSideCarHelper.track("tuoming");
        return masking(t, object);
    }

    default String baseEgMasking(String eg, char mask, String object) {
        SafeSideCarHelper.track("tuoming");
        //region 先依照示例来脱敏
        char[] chars = object.toCharArray();
        StringBuilder stringBuilder = new StringBuilder(chars.length);
        char[] egArray = eg.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = egArray[i];
            if (Objects.equals(c, mask)) {
                stringBuilder.append(mask);
            } else {
                stringBuilder.append(chars[i]);
            }
        }
        return stringBuilder.toString();
    }


    /**
     * 默认规则
     *
     * @param firstShow
     * @param lastShow
     * @param mask
     * @param object
     * @return
     */
    default String baseMasking(int firstShow, int lastShow, char mask, String object) {
        if (firstShow <= NumEnum.NAN.getValue() && lastShow <= NumEnum.NAN.getValue()) {
            return object;
        }
        int first = firstShow;
        int last = lastShow;
        if (first < 0) {
            first = 0;
        }
        if (last < 0) {
            last = 0;
        }
        char[] sourceObj = object.toCharArray();
        if (first + last >= sourceObj.length) {
            last = sourceObj.length - first;
            if (last < NumEnum.ZERO.getValue()) {
                last = NumEnum.ZERO.getValue();
            }
        }
        StringBuilder stringBuilder = new StringBuilder(sourceObj.length);
        if ((first | last) <= NumEnum.ZERO.getValue()) {
            for (char ignored : sourceObj) {
                stringBuilder.append(mask);
            }
            return stringBuilder.toString();
        }
        int endLast = sourceObj.length - last;
        for (int i = NumEnum.ZERO.getValue(); i < sourceObj.length; i++) {
            if (i <= first - NumEnum.ONE.getValue()) {
                stringBuilder.append(sourceObj[i]);
                continue;
            }
            if (i >= endLast) {
                stringBuilder.append(sourceObj[i]);
                continue;
            }
            stringBuilder.append(mask);
        }
        return stringBuilder.toString();
    }

}
